package perso.marcr.lst.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import perso.marcr.lst.param.GlobalParameters;
import perso.marcr.lst.service.JobService;

@Service
public class JobServiceImpl implements JobService {

	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#jobExists(java.lang.String)
	 */
	public boolean jobExists(String jobName) {
		String szJobDirectory = GlobalParameters.getJobDirectory(jobName);
		return new File(szJobDirectory).exists();
	}

	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#jobWellFormed(java.lang.String)
	 */
	public boolean jobNameWellFormed(String jobName) {
		return jobName.matches(JOB_NAME_REGEXPR);
	}

	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#getAllJobs()
	 */
	public List<String> getAllJobs() {
		String jobsDirectory = GlobalParameters.getJobDirectory();
		File dir = new File(jobsDirectory);

		File[] files = dir.listFiles();

		// This filter only returns directories
		FileFilter fileFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory();
			}
		};
		files = dir.listFiles(fileFilter);

		// build result:
		List<String> result = new ArrayList<String>();
		for(int i=0; i<files.length; i++)
		{
			String jobName=files[i].getName();
			if(jobNameWellFormed(jobName)){
				result.add(files[i].getName());
			}
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#create(java.lang.String)
	 */
	public void create(String jobName) {
		String jobsDirectory = GlobalParameters.getJobDirectory(jobName);
		new File(jobsDirectory).mkdirs();
	}


	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#delete(java.lang.String)
	 */
	public void delete(String jobName) throws IOException {
		if(jobName!=null && !jobName.isEmpty() && !jobName.contains("/"))
		{
			String szJobDirectory = GlobalParameters.getJobDirectory(jobName);
			FileUtils.deleteDirectory(new File(szJobDirectory));
		}
	}

	/* (non-Javadoc)
	 * @see perso.marcr.lst.service.JobService#renameJob(java.lang.String, java.lang.String)
	 */
	public void renameJob(String oldJobName, String newJobName) throws IOException {
		FileUtils.moveDirectory(new File(GlobalParameters.getJobDirectory(oldJobName)), new File(GlobalParameters.getJobDirectory(newJobName)));
	}


}
